<?php

namespace App\Store\Models\Wxapp\Gift;

use App\Common\Services\Common;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;

class WxappGiftStocklist extends Model
{
    protected $table = 'site_wxapp_gift_stocklist';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];

    public static function getList(Request $request)
    {
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $query = self::with(['gift_category_info','store_info'])->where('is_del', 1)->where('cp_id',$cp_id)->orderBy('create_at', 'desc');

        $store_ids = StoreCommon::getCurrentAccountStoreId($request);
        if($store_ids){//权限控制
            if(is_numeric($store_ids) && intval($store_ids)>0){//获取当前门店下的列表
                $query->where('store_id', intval($store_ids));
            }
        }


        $store_id = intval($request->store_id);
        if ($store_id>0) {
            $query->where('store_id', $store_id);
        }

        $gift_category_id = intval($request->gift_category_id);
        if ($gift_category_id>0) {
            $query->where('gift_category_id', $gift_category_id);
        }

        $gift_name = $request->gift_name;
        if ($gift_name!='') {
            $query->where('gift_name', 'like','%'.$gift_name.'%');
        }
        

        $isgetall = intval($request->isgetall) ?? 0;
        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return Common::paginateDataToArray($list);
        } else {
            $list = $query->get()->toArray();
            return ['list' => $list];
        }
    }


    public static function getListByMem(Request $request,$cp_id)
    {
        $query = self::where(['is_del'=>1,'cp_id'=>$cp_id,'store_id'=>0])
        ->where(function ($q){
            $q->where('valid_end_at',0)->orWhere('valid_end_at','>=',time());
        })
        ->orderBy('create_at', 'desc');
        $limit = $request->limit ?? 10;
        $list = $query->paginate($limit)->toArray();
        return Common::paginateDataToArray($list);
    }

    public function gift_category_info(){
        return $this->hasOne(WxappGiftCategory::class,'id','gift_category_id')->select(['id','category_name']);
    }

    public function store_info(){
        return $this->hasOne(SiteStore::class,'id','store_id')->select(['id','store_name']);
    }
}